package com.comment.service;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import com.comment.domain.Account;
import com.comment.util.HibernateUtils;
import com.comment.util.MD5Utils;

/**
 * 账户
 * 
 * @author Wangpeihu
 * @team [Never give up]
 * @since JDK1.6(建议)
 * @date 2010-5-15
 */
public class AccountService {
	@SuppressWarnings("unchecked")
	public Account validateAccount(String name, String password) {
		Session session = HibernateUtils.getSession();
		Query query = session
				.createQuery("from Account where name=? and password=?");
		query.setParameter(0, name);
		query.setParameter(1, MD5Utils.md5(password));
		List<Account> list = query.list();
		Account account = null;
		if (list.size() > 0) {
			account = (Account) list.get(0);
		}
		session.close();
		return account;
	}

	/**
	 * 
	 * @param account
	 */
	public void insertAccount(Account account) {
		Session session = HibernateUtils.getSession();
		Transaction tx = session.beginTransaction();
		try {
			account.setPassword(MD5Utils.md5(account.getPassword()));
			session.save(account);
			tx.commit();
		} catch (HibernateException e) {
			tx.rollback();
			throw e;
		} finally {
			session.close();
		}
	}

	@Test
	public void testInsertAccount() {
		Account account = new Account();
		account.setName("王培虎");
		account.setPassword("0");
		insertAccount(account);
	}

	public static void main(String[] args) {
		AccountService a = new AccountService();
		a.testInsertAccount();
	}
}
